//
//  HTAutherInfoViewController.m
//  HeartTravel
//
//  Created by lanou on 15/10/29.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTAutherInfoViewController.h"
#import "HTAutherInfoView.h"
#import "PKRequestManager.h"
#import "UIImageView+WebCache.h"
#import "HTTieZiTableViewCell.h"
#import "HTShareTableViewCell.h"
#import <MediaPlayer/MediaPlayer.h>
@interface HTAutherInfoViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *mainListTableView;
@property (nonatomic, strong) NSMutableArray *headerDataArray;
@property (nonatomic, strong) NSMutableArray *tieZiDataArray;
@property (nonatomic, strong) NSMutableArray *shareDataArray;
@property (nonatomic, strong) HTAutherInfoView *headerView;
@property (nonatomic, assign) NSInteger index;

@end

@implementation HTAutherInfoViewController

- (NSMutableArray *)headerDataArray{
    if (!_headerDataArray) {
        _headerDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _headerDataArray;
}
- (void)requestHeaderDataSource
{
    NSString *urlString = [@"http://api.budejie.com/api/api_open.php?a=profile&appname=baisishequ&asid=9B8A36AE-96F8-4D1B-8850-D39ECA7F54FD&c=user&client=iphone&device=ios%20device&jbk=0&mac=&market=&openudid=5fd2dd7c3e13e78bbc5119f9f1405e9ed2bdd82f&udid=&userid=" stringByAppendingFormat:@"%@%@", self.u_id, @"&ver=3.7"];
    [PKRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dic = dict[@"data"];
        [self.headerView.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"background_image"]]];
        self.headerView.nameLabel.text = dic[@"username"];
        [self.headerView.iconImageView sd_setImageWithURL:[NSURL URLWithString:dic[@"profile_image"]]];
        self.headerView.rankLabel.text = [NSString stringWithFormat:@"%@", dic[@"level"]];
        self.headerView.pointLabel.text = [NSString stringWithFormat:@"%@", dic[@"experience"]];
        self.headerView.followLabel.text = dic[@"follow_count"];
        self.headerView.likeNumLabel.text = dic[@"fans_count"];
        self.headerView.tieZiLabel.text = [NSString stringWithFormat:@"%@", dic[@"tiezi_count"]];
        self.headerView.shareLabel.text = dic[@"share_count"];
        self.headerView.commentLabel.text = dic[@"comment_count"];
    } error:^(NSError *error) {
        
    }];
}

- (NSMutableArray *)tieZiDataArray{
    if (!_tieZiDataArray) {
        _tieZiDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _tieZiDataArray;
}

- (void)requestTieZiDataSource{
    NSString *urlString = [@"http://s.budejie.com/topic/user-topic/" stringByAppendingFormat:@"%@%@", self.u_id, @"/1/desc/baisishequ-iphone-3.7/0-20.json?appname=baisishequ&asid=9B8A36AE-96F8-4D1B-8850-D39ECA7F54FD&client=iphone&device=ios%20device&from=ios&jbk=0&mac=&market=&openudid=5fd2dd7c3e13e78bbc5119f9f1405e9ed2bdd82f&show_top=1&udid=&ver=3.7"];
    [PKRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *dic in dict[@"list"]) {
            HTVideoMainListModel *model = [[HTVideoMainListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.tieZiDataArray addObject:model];
        }
        [self.mainListTableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"作者帖子栏数据请求失败%@", error);
    }];
}
- (NSMutableArray *)shareDataArray{
    if (!_shareDataArray) {
        _shareDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _shareDataArray;
}
- (void)requestShareDataSource{
    NSString *urlString = [@"http://s.budejie.com/topic/share-topic/" stringByAppendingFormat:@"%@%@", self.u_id, @"/baisishequ-iphone-3.7/1442739910-20.json?appname=baisishequ&asid=9B8A36AE-96F8-4D1B-8850-D39ECA7F54FD&client=iphone&device=ios%20device&from=ios&jbk=0&mac=&market=&openudid=5fd2dd7c3e13e78bbc5119f9f1405e9ed2bdd82f&udid=&ver=3.7"];
    [PKRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *dic in dict[@"list"]) {
            HTVideoMainListModel *model = [[HTVideoMainListModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.shareDataArray addObject:model];
        }
        [self.mainListTableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"作者分享界面数据请求失败%@", error);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestHeaderDataSource];
    [self requestTieZiDataSource];
    [self requestShareDataSource];
    
    self.topView.backgroundColor = [UIColor colorWithRed:0.351 green:0.359 blue:0.350 alpha:1.000];
    [self.leftButton addTarget:self action:@selector(didClickBack) forControlEvents:(UIControlEventTouchUpInside)];
    [self.leftButton setBackgroundImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
    self.titleLabel.frame = CGRectMake(80, 10, SCREEN_WIDTH - 160, 30);
    self.titleLabel.font = [UIFont systemFontOfSize:18];
    self.titleLabel.textColor = [UIColor blackColor];
    self.titleLabel.text = self.name;
    [self addMainListTableView];
    
    [self addHeaderView];
    
}
- (void)addHeaderView{
    _headerView = [[[UINib nibWithNibName:@"HTAutherHeaderView" bundle:nil] instantiateWithOwner:self options:nil]firstObject];
    _headerView.iconImageView.layer.cornerRadius = 35;
    _headerView.iconImageView.layer.masksToBounds = YES;
    _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 380);
    [_headerView.tieZiButton addTarget:self action:@selector(didClickChange:) forControlEvents:(UIControlEventTouchUpInside)];
    _headerView.tieZiButton.tag = 10;
    [_headerView.shareButton addTarget:self action:@selector(didClickChange:) forControlEvents:(UIControlEventTouchUpInside)];
    _headerView.shareButton.tag = 20;
    self.mainListTableView.tableHeaderView = _headerView;
}
- (void)didClickChange:(UIButton *)sender{
    [_headerView.tieZiButton setTitle:@"帖子" forState:(UIControlStateNormal)];
    [_headerView.tieZiButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [_headerView.shareButton setTitle:@"分享" forState:(UIControlStateNormal)];
    [_headerView.shareButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [sender setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    _index = sender.tag;
    [self.mainListTableView reloadData];
}

- (void)addMainListTableView{
    _mainListTableView = [[UITableView alloc]init];
    _mainListTableView.frame = CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT - 120);
    _mainListTableView.dataSource = self;
    _mainListTableView.delegate = self;
    [_mainListTableView registerClass:[HTTieZiTableViewCell class] forCellReuseIdentifier:@"HTTieZiTableViewCell"];
    [_mainListTableView registerClass:[HTShareTableViewCell class] forCellReuseIdentifier:@"HTShareTableViewCell"];
    [self.view addSubview:_mainListTableView];
}
- (void)didClickBack{
    [self.navigationController popViewControllerAnimated:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   if (_index == 20){
        
        return self.shareDataArray.count;
    }
    return self.tieZiDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_index == 20){
        HTShareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HTShareTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.configureModel = self.shareDataArray[indexPath.row];
        return cell;
    }
    HTTieZiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HTTieZiTableViewCell" forIndexPath:indexPath];
    cell.configureModel = self.tieZiDataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.playButton addTarget:self action:@selector(didClickToPlayVideo:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.videoImageView.userInteractionEnabled = YES;
    cell.playButton.tag = 1000 + indexPath.row;
#warning 判断当前是否添加视频播放器View, 如果添加将其从父视图移除,否则点击某个播放器播放过程中加载cell, 会导致bug
    if (cell.videoImageView.subviews.count > 3) {
        [cell.videoImageView.subviews.lastObject removeFromSuperview];
    }

    return cell;
}
// 点击播放视频按钮事件
- (void)didClickToPlayVideo:(UIButton *)sender
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag - 1000 inSection:0];
    HTVideoMainListModel *model = self.tieZiDataArray[indexPath.row];
    HTTieZiTableViewCell *cell = [self.mainListTableView cellForRowAtIndexPath:indexPath];
    // 初始化播放器
    self.moviePlayerController = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:model.video.video[0]]];
    
    self.moviePlayerController.view.frame = CGRectMake(0, 0, cell.videoImageView.frame.size.width, cell.videoImageView.frame.size.height);
    [cell.videoImageView addSubview:_moviePlayerController.view];
    [self.moviePlayerController play];
    
    //    播放结束的时候添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

- (void)playerFinish:(id)sender
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    // 卸载监听, 保证程序不会崩溃
    [_moviePlayerController.view removeFromSuperview];
    _moviePlayerController = nil;// 释放资源
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_index == 20){
        
        return [HTShareTableViewCell heightForCell:self.shareDataArray[indexPath.row]];
    }
    return [HTTieZiTableViewCell heightForCell:self.tieZiDataArray[indexPath.row]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
